import React from 'react';
import { Button, Space } from 'antd';
import { PlusOutlined, EditOutlined } from '@ant-design/icons';
import CommonFormModal from '../components/CommonFormModal';
import { useFormModal } from '../hooks/useFormModal';
import { productFormConfig } from '../utils/formConfigs';

// 测试数据类型
interface TestData {
  id: string;
  code: string;
  name: string;
  warningStock: number;
  category: string;
}

// 模拟数据
const mockData: TestData[] = [
  {
    id: '1',
    code: 'TEST001',
    name: '测试产品1',
    warningStock: 10,
    category: '小家电'
  },
  {
    id: '2',
    code: 'TEST002',
    name: '测试产品2',
    warningStock: 20,
    category: '大家电'
  }
];

const TestForm: React.FC = () => {
  const [data, setData] = React.useState<TestData[]>(mockData);
  
  const {
    visible,
    isAddMode,
    currentRecord,
    loading,
    openAddModal,
    openEditModal,
    closeModal,
  } = useFormModal<TestData>();

  // 处理提交
  const handleSubmit = async (values: Record<string, unknown>, isAddMode: boolean, currentRecord?: TestData | null) => {
    console.log('提交数据:', { values, isAddMode, currentRecord });
    
    if (isAddMode) {
      // 新增
      const newItem: TestData = {
        id: Date.now().toString(),
        code: values.code as string,
        name: values.name as string,
        warningStock: values.warningStock as number,
        category: values.category as string,
      };
      setData([...data, newItem]);
    } else {
      // 编辑
      const updatedData = data.map(item =>
        item.id === currentRecord?.id
          ? {
              ...item,
              code: values.code as string,
              name: values.name as string,
              warningStock: values.warningStock as number,
              category: values.category as string,
            }
          : item
      );
      setData(updatedData);
    }
  };

  return (
    <div style={{ padding: '20px' }}>
      <h2>通用表单组件测试</h2>
      
      <Space style={{ marginBottom: '20px' }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={openAddModal}>
          新增产品
        </Button>
        <Button 
          icon={<EditOutlined />} 
          onClick={() => openEditModal(data[0])}
          disabled={data.length === 0}
        >
          编辑第一个产品
        </Button>
      </Space>

      <div>
        <h3>当前数据:</h3>
        <pre>{JSON.stringify(data, null, 2)}</pre>
      </div>

      <CommonFormModal
        visible={visible}
        title={isAddMode ? "新增产品" : "编辑产品"}
        isAddMode={isAddMode}
        currentRecord={currentRecord}
        formItems={productFormConfig}
        onSubmit={handleSubmit}
        onCancel={closeModal}
        loading={loading}
        width={600}
      />
    </div>
  );
};

export default TestForm;
